import {Component, OnInit} from '@angular/core';
import {moveItemInArray} from '@angular/cdk/drag-drop';
import {NzMessageService} from 'ng-zorro-antd/message';
import {ActivatedRoute, Router} from '@angular/router';
import {AssessPriceService} from '../../assess-price.service';

// 题目
interface Question {
  id: string; // 题目id
  questionName: string; // 题目名称
  internalName: string; // 内部题目名称
  selectType: 0 | 1; // 题目是多选还是单选 0-单选  1-多选
  isRequired: boolean; // 是否是必选 0-非必选  1-必选
  options: Option[]; // 选项
}

// 选项
interface Option {
  id: string;
  optionName: string; // 选项名称
  selectAble: boolean; // 是否可选 0-不可选 1-可选
  invalidCause: string; // 不可选理由
  used: boolean; // 是否是二手 0-准新 1-二手
  questionId: any; // 要跳转的题目的id
  optionRemark: string; // 选项描述
  optionImages: string[]; // 选项图片
  deleteState: number; // 选项删除状态
}

@Component({
  selector: 'app-question-edit',
  templateUrl: './question-edit.component.html',
  styleUrls: ['./question-edit.component.scss']
})
export class QuestionEditComponent implements OnInit {
  readonly = false;
  // 是否已经保存
  isSaved = false;
  questionData: Question = {
    id: '',
    questionName: '',
    internalName: '',
    selectType: 0,
    isRequired: true,
    options: [{
      id: '',
      optionName: '',
      selectAble: true,
      invalidCause: '',
      used: true,
      questionId: null,
      deleteState: 0,
      optionRemark: '',
      optionImages: []
    }],
  };

  constructor(
    private nzMessageService: NzMessageService,
    private activatedRoute: ActivatedRoute,
    private assessPriceService: AssessPriceService,
    private router: Router,
  ) {
  }

  ngOnInit(): void {
    const routerQueryParams = this.activatedRoute.snapshot.queryParams;
    if (routerQueryParams?.id) {
      this.assessPriceService.getQuestionDetail(routerQueryParams.id).then((res: any) => {
        if (res.code === 0) {
          console.log(res);
          this.readonly = routerQueryParams.type === 'edit' ? res.data.isQuote === 1 : false;
          this.questionData.id = routerQueryParams.type === 'edit' ? res.data.recycleEvalQuestion.id : '';
          this.questionData.questionName = res.data.recycleEvalQuestion.questionName;
          this.questionData.internalName = res.data.recycleEvalQuestion.internalName;
          this.questionData.selectType = res.data.recycleEvalQuestion.selectType;
          this.questionData.isRequired = res.data.recycleEvalQuestion.isRequired === 1;
          this.questionData.options = res.data.recycleEvalOptions.map((q: any) => {
            return {
              ...q,
              used: q.used === 1,
              selectAble: q.selectAble === 1,
              optionImages: q.optionImages ? q.optionImages.split(',') : []
            };
          });
        }
      });
    }
  }

  // 删除图片
  removeImg(index: any, optionIndex: any) {
    console.log(optionIndex, index);
    this.questionData.options[optionIndex].optionImages.splice(index, 1);
  }

  // 添加图片
  appendImg(url: string, optionIndex: any) {
    this.questionData.options[optionIndex].optionImages.push(url);
  }

  // 删除选项
  removeOption(optionIndex: number) {
    if (this.questionData.options.filter((o: any) => o.deleteState === 0).length <= 1) {
      this.nzMessageService.warning('至少需要一个选项');
      return;
    }
    this.questionData.options[optionIndex].deleteState = 1;
  }

  // 拖拽选项
  dropOption(event: any) {
    moveItemInArray(this.questionData.options, event.previousIndex, event.currentIndex);
  }

  // 添加选项
  addOption() {
    if (this.verifyNullOption(this.questionData.options)) {
      this.nzMessageService.warning('存在未填写的选项');
    } else {
      this.questionData.options.push({
        id: '',
        optionName: '',
        selectAble: true,
        invalidCause: '',
        used: true,
        questionId: null,
        optionRemark: '',
        deleteState: 0,
        optionImages: []
      });
    }
  }

  // 检查是否有空选项
  verifyNullOption(options: Option[]) {
    if (options.length) {
      return options.some(option => option.optionName === '' && option.deleteState === 0);
    } else {
      return false;
    }
  }

  saveQuestion() {
    if (!this.questionData.questionName) {
      this.nzMessageService.warning('请输入题目名称');
      return;
    }
    if (!this.questionData.internalName) {
      this.nzMessageService.warning('请输入内部名称');
      return;
    }
    if (this.questionData.options.some(o => !o.selectAble && !o.invalidCause)) {
      this.nzMessageService.warning('不可选理由不能为空');
      return;
    }
    if (this.verifyNullOption(this.questionData.options)) {
      this.nzMessageService.warning('存在未填写的选项');
      return;
    }
    const recycleEvalQuestion = {
      id: this.questionData.id,
      questionName: this.questionData.questionName,
      internalName: this.questionData.internalName,
      selectType: this.questionData.selectType,
      isRequired: this.questionData.isRequired ? 1 : 0,
    };
    const recycleEvalOptionList = this.questionData.options.map((q: any, index: number) => {
      return {
        ...q,
        sort: index,
        used: q.used ? 1 : 0,
        selectAble: q.selectAble ? 1 : 0,
        optionImages: q.optionImages.join(','),
        deleteState: q.deleteState
      };
    });
    if (this.questionData.id) {
      this.assessPriceService.updateQuestion(recycleEvalQuestion, recycleEvalOptionList).then((res: any) => {
        if (res.code === 0) {
          this.nzMessageService.success('修改成功');
          this.isSaved = true;
          this.back();
        }
      });
    } else {
      this.assessPriceService.addQuestion(recycleEvalQuestion, recycleEvalOptionList).then((res: any) => {
        if (res.code === 0) {
          this.nzMessageService.success('添加成功');
          this.isSaved = true;
          this.back();
        }
      });
    }
  }

  back() {
    this.router.navigate(['/aisi-recyc/assessPriceQuestionList']);
  }
}
